package notify

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
)

const (
	_qyWechatURL  = "https://qyapi.weixin.qq.com"
	_corpID       = "ww408a692c72ddf86e"
	_departmentID = "7"
	_agentID      = 1000018
	_corpSecret   = "ez3WBQ5cJUHnpt-J-RmMD1ltI0DWx9ysRpC9fEU2qOE"
	_getToken     = "/cgi-bin/gettoken"
	_sendMessage  = "/cgi-bin/message/send"
)

// Token query access token with the specified secret 企业微信api获取公司token
func Token() (string, error) {
	u := _qyWechatURL + _getToken
	req, err := http.NewRequest("GET", u, nil)
	if err != nil {
		return "", err
	}
	q := req.URL.Query()
	q.Add("corpid", _corpID)
	q.Add("corpsecret", _corpSecret)
	req.URL.RawQuery = q.Encode()
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer func() { _ = resp.Body.Close() }()
	res := struct {
		ErrCode     int    `json:"errcode"`
		ErrMsg      string `json:"errmsg"`
		AccessToken string `json:"access_token"`
		ExpiresIn   int    `json:"expires_in"`
	}{}
	_ = json.NewDecoder(resp.Body).Decode(&res)
	if res.ErrCode != 0 {
		return "", errors.New(res.ErrMsg)
	}
	return res.AccessToken, nil
}

// SendMarkDown 发送markdown消息
func SendMarkDown(msg string) (err error) {
	var (
		u        string
		req      *http.Request
		token    string
		bodyJSON []byte
	)
	token, err = Token()
	if err != nil {
		return err
	}
	bodyJSON = []byte(fmt.Sprintf(`{"toparty": "%s", "msgtype": "%s", "agentid": %d, "markdown": {"content": "%s"}}`, _departmentID, "markdown", _agentID, msg))
	u = _qyWechatURL + _sendMessage
	req, err = http.NewRequest("POST", u, bytes.NewBuffer(bodyJSON))
	if err != nil {
		return
	}
	q := req.URL.Query()
	q.Add("access_token", token)
	req.URL.RawQuery = q.Encode()
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	defer func() { _ = resp.Body.Close() }()
	if err != nil {
		return
	}
	return
}
